<template>
	<view class="setVideo_box">
		<!-- 头部返回上一页 -->
		<view class="top_back" @click="backTo">
			<image src="https://yy.dx1126.cn/images/back.png" mode=""></image>
		</view>
		<!-- 视频展示 -->
		<view class="videoYuLan" @click="closeMudio">
			<!--
			 autoplay	Boolean	false	是否自动播放
			 danmu-list	Object Array		弹幕列表
			 @error 视频报错触发
			 page-gesture	Boolean	false	在非全屏模式下，是否开启亮度与音量调节手势
			 vslide-gesture	Boolean	false	在非全屏模式下，是否开启亮度与音量调节手势（同 page-gesture）
			 @ended	EventHandle		当播放到末尾时触发 ended 事件
			 loop   是否循环播放
			 show-fullscreen-btn	Boolean	true	是否显示全屏按钮
			 show-play-btn	Boolean	true	是否显示视频底部控制栏的播放按钮
			 show-center-play-bt n	Boolean	true	是否显示视频中间的播放按钮
			 object-fit	String	contain	当视频大小与 video 容器大小不一致时，视频的表现形式。contain：包含，fill：填充，cover：覆盖
			 direction	Number		设置全屏时视频的方向，不指定则根据宽高比自动判断。有效值为 0（正常竖向）, 90（屏幕逆时针90度）, -90（屏幕顺时针90度）
			 enable-play-gesture	Boolean	false	是否开启播放手势，即双击切换播放/暂停
			 -->
			<video :src="src" :autoplay='true' :controls="false" :show-center-play-bt="false" :loop="true"
				:enable-play-gesture="true" :muted="shengBob"></video>
			<!-- 背景音乐 -->
		</view>

		<!-- 视频背景音乐设置和下一步 -->
		<view class="medioToSetContent">
			<view class="mudio" @click="mudioChange">
				<image src="https://yy.dx1126.cn/images/mudio.png" mode=""></image>
				<text>配乐</text>
			</view>
			<view class="toSetContent" @click="aucioVideoMerge">
				<text>下一步</text>
				<image src="https://yy.dx1126.cn/images/xai.png" mode=""></image>
			</view>
		</view>

		<!-- 音乐的选择弹窗 -->
		<view class="mudios" :style="{height:mudioBob?'600rpx':'0',zIndex:addBobs?29:30}">
			<!-- 音乐列表 -->
			<view class="mudioList">
				<view class="list_item" v-for="(item,index) in mudioList" :key="item.id"
					:class="{'mudioActive':item.id ==indexBob}" @click="selectItem(item.id)">
					<view class="image_feng">
						<image :src="item.src" mode=""></image>
					</view>
					<view class="mudio_content">
						<text class="xuans">{{item.title}}</text>
						<view class="text2">
							<text>{{item.singer}}</text>
						</view>

					</view>
					<!-- 删除音频 -->
					<image class="shanChu" src="https://yy.dx1126.cn/images/close.png"
						@click.stop="shanChuAudio(index)">
					</image>
					<!-- 下载音频 -->
					<image class="shanChu1 image" src="../../public/images/xia.png" @click.stop="xiaZaiVideo(item.url)">

					</image>
				</view>
			</view>
			<!-- 设置背景声音 -->
			<view class="mudios_bottom">
				<view class="bottom_left" @click="changeMudio">
					<view class="status">
						<text v-show="!shengBob" class="min_text"></text>
						<image src="https://yy.dx1126.cn/images/xuanz.png" mode="" v-show="shengBob"></image>
					</view>
					<text>配乐</text>
				</view>

				<view class="bottom_left" @click="changeMudio">
					<view class="status">
						<text v-show="shengBob" class="min_text"></text>
						<image src="https://yy.dx1126.cn/images/xuanz.png" mode="" v-show="!shengBob"></image>
					</view>
					<text>原声</text>
				</view>

				<view class="addAudio" @click="addChangs">
					<text>添加音频</text>
				</view>
			</view>


		</view>

		<!-- 添加音乐 -->
		<view class="addAudio_fa" :style="{height:mudioBob?'600rpx':'0',zIndex:addBobs?30:29}">
			<!-- 填写信息 -->
			<view class="inputs">
				<!-- 封面 -->
				<view class="srcs" @click="srcChange">
					<text>封面:</text>
					<image :src="srcAudio" mode=""></image>
				</view>
				<!--视频 -->
				<view class="urls" @click="urlChange">
					<text>音频:</text>
					<image src="https://yy.dx1126.cn/images/jia.png" v-show="urlBob"></image>
					<image src="https://yy.dx1126.cn/images/dui.png" v-show="!urlBob"></image>
				</view>
				<!-- 歌名 -->
				<view class="titles">
					<text>名称:</text><input type="text" :value="titleName" @input="titleInput">
				</view>
				<!-- 歌手 -->
				<view class="singer">
					<text>歌手:</text><input type="text" :value="singer" @input="singerInput">
				</view>
			</view>

			<!-- 选择 -->
			<view class="mudios_bottom">
				<view class="bottom_left" @click="closeAudio">
					<text>取消添加</text>
				</view>

				<view class="addAudio" @click="addAudio">
					<text>确认添加</text>
				</view>
			</view>

		</view>

	</view>
</template>

<script setup>
	import {
		onUnmounted,
		ref
	} from 'vue'
	import {
		onLoad,
		onShow,
		onHide
	} from '@dcloudio/uni-app'
	import {
		useIndexStore
	} from '@/store/pinia.js';
	import {
		error
	} from 'console';

	// 数据仓库
	let store = useIndexStore()

	// 下载视频
	const xiaZaiVideo = (url) => {
		// 获取存入相册的权限
		uni.authorize({
			scope: 'scope.writePhotosAlbum',
			success() {
				// 将视频存入相册
				uni.saveVideoToPhotosAlbum({
					// 文件路径
					filePath: url,
					success: function() {
						uni.showToast({
							title: '下载成功',
							duration: 2000
						});
					},
					fail: (e) => {
						uni.showToast({
							title: '不能下载示例,下载失败',
							icon: 'none',
							duration: 2000
						});
					}
				});
			},
			fail: () => {
				uni.showToast({
					title: '没有权限,下载失败',
					icon: 'error',
					duration: 2000
				});
			}
		})
	}

	// 页面路由对象
	let pages = getCurrentPages()
	// 视频地址
	let src = ref('')
	onLoad((query) => {
		// 获取传过来的视频地址，播放
		src.value = query.src;
	})

	// 选择声音  默认原声
	// 音乐列表
	let mudioList = ref(store.mudios)
	const changeMudio = () => {
		shengBob.value = !shengBob.value
		if (shengBob.value) {
			innerAudioContext.play()
		} else {
			innerAudioContext.pause()
		}
	}

	// 切换添加
	let addBobs = ref(false)
	const addChangs = () => {
		addBobs.value = true
	}

	// 添加音频
	// 选择封面
	let srcAudio = ref('https://yy.dx1126.cn/images/jia.png')
	const srcChange = () => {
		// 选择图片文件
		uni.chooseMedia({
			count: 1,
			mediaType: ['image'],
			sourceType: ['album'],
			success(res) {
				srcAudio.value = res.tempFiles[0].tempFilePath
			}
		})
	}
	// 选择音频
	let urlAudio = ref('')
	let urlBob = ref(true)
	const urlChange = () => {
		uni.chooseMedia({
			count: 1,
			mediaType: ['audio'],
			sourceType: ['album'],
			success(res) {
				let audioHou = res.tempFiles[0].tempFilePath.split('.')[res.tempFiles[0].tempFilePath.split(
						'.')
					.length - 1]
				if (audioHou == 'CD' || audioHou == 'cd' || audioHou == 'mp3' || audioHou == 'MP3' ||
					audioHou == 'WAVE' || audioHou == 'wave' || audioHou == 'MPEG' || audioHou == 'mpeg' ||
					audioHou == 'AIFF' || audioHou == 'aiff' || audioHou == 'WMA' || audioHou == 'wma' ||
					audioHou == 'AAC' || audioHou == 'aac' || audioHou == 'ogg' || audioHou == 'OGG') {
					urlAudio.value = res.tempFiles[0].tempFilePath
					urlBob.value = false
				} else {
					uni.showToast({
						title: '音频格式错误',
						icon: 'error',
					})
				}


			}
		})
	}
	// 歌名
	let titleName = ref('')
	const titleInput = (e) => {
		titleName.value = e.detail.value
	}
	// 歌手
	let singer = ref('')
	const singerInput = (e) => {
		singer.value = e.detail.value
	}
	// 取消
	const closeAudio = () => {
		addBobs.value = false
		setTimeout(() => {
			srcAudio.value = 'https://yy.dx1126.cn/images/jia.png'
			urlAudio.value = ''
			urlBob.value = true
			titleName.value = ''
			singer.value = ''
		})
	}
	// 添加
	const addAudio = () => {
		if (srcAudio.value == 'https://yy.dx1126.cn/images/jia.png' || urlAudio.value == '' || titleName.value == '' ||
			singer.value == '') {
			uni.showToast({
				title: '信息不得为空',
				icon: 'none',
			})
			return
		}
		let id = mudioList.value.length + Math.floor(Math.random() * 1000)
		let obj = {
			id,
			src: srcAudio.value,
			url: urlAudio.value,
			title: titleName.value,
			singer: singer.value
		}
		mudioList.value.unshift(obj)
		uni.setStorageSync('audio', mudioList.value);
		closeAudio()
	}

	// 删除音乐
	const shanChuAudio = (index) => {
		uni.showModal({
			title: "确认删除该音乐吗?",
			success: function(res) {
				if (res.confirm) {
					mudioList.value.splice(index, 1)
					uni.setStorageSync('audio', mudioList.value);
				}
			}
		})

	}


	// 音乐选择
	let indexBob = ref(0)
	// 创建音乐的上下文对象
	let innerAudioContext = uni.createInnerAudioContext();
	onShow(() => {
		innerAudioContext = uni.createInnerAudioContext();
	})
	// 选择声音  默认原声
	let shengBob = ref(false)
	// 音频地址
	let audioSrc = ref('')
	const selectItem = async (id) => {
		try {
			/* 获取音乐url   getSongDetail.data[0].url */
			let getUrl = mudioList.value.find(item => item.id == id).url
			// 自动播放
			innerAudioContext.autoplay = true;
			shengBob.value = true

			// 循环播放
			innerAudioContext.loop = true;
			// 播放地址
			innerAudioContext.src = getUrl
			audioSrc.value = getUrl
			// 中止其他声音播放，不能后台播放，静音后无声音；
			innerAudioContext.sessionCategory = "soloAmbient"

			// 开始播放的成功回调函数
			innerAudioContext.onPlay(() => {
				uni.showToast({
					title: '开始播放',
					duration: 2000
				});
			});
			// 播放错误
			innerAudioContext.onError((res) => {
				uni.showToast({
					title: '播放错误',
					icon: 'error',
					duration: 2000
				});
			});
			// 更改播放音乐的样式
			indexBob.value = id
		} catch (err) {
			uni.showToast({
				title: '音乐请求失败',
				icon: 'error',
				duration: 2000
			});
			console.log(err);
		}
	}


	// 合并音频视频并进入下一步

	const aucioVideoMerge = () => {
		console.log('待完成');
		// 跳转发布页
		uni.navigateTo({
			url: '/pages/faBuVideo/faBuVideo?src=' + src.value
		})

		// console.log('启动', src.value, audioSrc.value);
		// let mc = uni.createMediaContainer()
		// // 视频轨道
		// let vt = mc.extractDataSource({
		// 	source: src.value
		// })
		// // 音频轨道
		// let at = mc.extractDataSource({
		// 	source: audioSrc.value,
		// })
		// console.log(mc);
		// // 轨道添加到容器中
		// mc.addTrack(vt)
		// mc.addTrack(at)
		// let newVideo = mc.export()
		// console.log("新的视频：", newVideo);
		// //合成之后将容器销毁，释放资源
		// mc.destroy()
	}



	// 返回上一页
	const backTo = () => {
		uni.navigateBack(1)
	}

	// 视频弹窗
	let mudioBob = ref(false)
	const mudioChange = () => {
		mudioBob.value = !mudioBob.value
	}
	// 点击视频关闭弹窗
	const closeMudio = () => {
		uni.showToast({
			title: '双击视频暂停或者播放',
			icon: 'none',
			duration: 1000
		});
		mudioBob.value = false
	}

	// 离开页面销毁实例
	onHide(() => {
		innerAudioContext.destroy()
	})
	onUnmounted(() => {
		innerAudioContext.destroy()
	})
</script>

<style lang="less">
	page {
		background-color: black;
	}

	.setVideo_box {
		width: 750rpx;
		height: 100%;

		// 返回上一页
		.top_back {
			width: 100rpx;
			height: 100rpx;
			padding: 25rpx 30rpx;
			position: fixed;
			top: 50rpx;
			left: 0;
			z-index: 20;

			image {
				width: 50rpx;
				height: 50rpx;
			}
		}

		//视频展示
		.videoYuLan {
			width: 100%;
			height: 100%;

			video {
				width: 100%;
				height: 100%;
			}

		}

		// 视频背景音乐设置和下一步
		.medioToSetContent {
			width: 100%;
			height: 120rpx;
			position: fixed;
			bottom: 20rpx;
			display: flex;
			justify-content: space-evenly;
			align-items: center;

			view {
				width: 45%;
				height: 80rpx;
				border-radius: 50px;
				color: white;
				display: flex;

				image {
					width: 50rpx;
					height: 50rpx;
					margin: auto;
				}

				text {
					margin: auto;
				}
			}

			.mudio {
				background-color: #33CCFF;
			}

			.toSetContent {
				background-color: #f63b68;
			}
		}

		// 配乐选择
		.mudios {
			width: 100%;
			height: 0;
			position: fixed;
			bottom: 0;
			z-index: 30;
			background-color: #212025;
			border-radius: 20px 20px 0 0;
			transition: all 0.5s ease-in-out;
			overflow: hidden;

			.mudioList {
				width: 100%;
				height: calc(100% - 60rpx);
				display: flex;
				flex-direction: column;
				overflow: auto;

				.list_item {
					width: 100%;
					border: 0.5px solid #27272a;
					display: flex;
					align-items: center;
					padding: 20rpx;
					color: white;
					position: relative;

					// 删除
					.shanChu {
						width: 40rpx;
						height: 40rpx;
						position: absolute;
						right: 30rpx;
					}

					// 下载
					.shanChu1 {
						width: 40rpx;
						height: 40rpx;
						position: absolute;
						right: 100rpx;
					}

					.image_feng {
						width: 70rpx;
						height: 70rpx;
						padding: 1rpx;
						border-radius: 10rpx;

						image {
							width: 100%;
							height: 100%;
							border-radius: 10rpx;

						}
					}

					.mudio_content {
						display: flex;
						flex-direction: column;
						margin-left: 20rpx;

						text {
							font-size: 26rpx;
						}

						.text2 {
							color: #777779;

							text {
								font-size: 20rpx;
								margin-right: 15rpx;
							}
						}
					}
				}

			}

			.mudios_bottom {
				width: 100%;
				height: 80rpx;
				display: flex;
				align-items: center;
				color: white;
				background-color: #212025;
				position: absolute;
				bottom: 0;
				padding: 0 30rpx;

				.bottom_left {
					margin-right: 30rpx;
				}

				view {
					display: flex;
					align-items: center;

					text {
						font-size: 28rpx;
					}

					.min_text {
						width: 30rpx;
						height: 30rpx;
						border: 1rpx solid white;
						border-radius: 50%;
						margin-right: 10rpx;

					}

					image {
						width: 30rpx;
						height: 30rpx;
						margin-right: 10rpx;
					}

				}

				.addAudio {
					position: absolute;
					right: 30rpx;

					text {
						font-size: 26rpx;
						height: 60rpx;
						line-height: 60rpx;
						color: white;
						background-color: transparent;
					}
				}
			}
		}


		// 添加音频
		.addAudio_fa {
			width: 100%;
			height: 0;
			position: fixed;
			bottom: 0;
			z-index: 19;
			background-color: #212025;
			border-radius: 20px 20px 0 0;
			transition: all 0.5s ease-in-out;
			overflow: hidden;

			.inputs {
				width: 100%;
				height: calc(100% - 80rpx);
				display: flex;
				flex-direction: column;
				justify-content: space-evenly;
				padding: 30rpx;

				view {
					display: flex;
					align-items: center;
				}

				image {
					width: 100rpx;
					height: 100rpx;
					border: 1rpx solid white;
					padding: 10rpx;
					border-radius: 8rpx;
				}

				text {
					width: 100rpx;
					color: white;
				}

				input {
					height: 60rpx;
					width: calc(100% - 100rpx);
					border: 1rpx solid white;
					border-radius: 10rpx;
					padding: 0 20rpx;
					color: white;

				}

			}

			.mudios_bottom {
				width: 100%;
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				color: white;
				background-color: #212025;
				position: absolute;
				bottom: 0;
				padding: 0 30rpx;

				.bottom_left {
					margin-right: 30rpx;

					text {
						font-size: 26rpx;
						height: 60rpx;
						line-height: 60rpx;
						color: white;
						background-color: rgba(246, 59, 104, 0.7);
						padding: 0 15rpx;
						border-radius: 8rpx;
					}
				}

				view {
					display: flex;
					align-items: center;

					text {
						font-size: 28rpx;
					}
				}

				.addAudio {
					margin-left: 40rpx;

					text {
						font-size: 26rpx;
						height: 60rpx;
						line-height: 60rpx;
						color: white;
						background-color: rgba(0, 128, 0, 0.7);
						padding: 0 15rpx;
						border-radius: 8rpx;
					}
				}
			}
		}
	}


	// 音乐选中状态
	.mudioActive {
		.image_feng {
			border: 1rpx solid #f03b6b;
		}

		.xuans {
			color: #f03b6b;
		}
	}
</style>